package com.niiwoo.civet.mobile.controller.loan;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.niiwoo.civet.trade.dto.response.loan.AgainstFakeModelV2CallbackRequestDTO;
import com.niiwoo.civet.trade.service.loan.antifraud.LoanAntiFraudDubboService;
import com.niiwoo.tripod.provider.exception.BizException;
import com.niiwoo.tripod.tiancheng.enums.AgainstFakeErrorCodeEnum;
import com.niiwoo.tripod.tiancheng.enums.FunctionCodeEnum;
import com.niiwoo.tripod.tiancheng.request.afp.AgainstFakeModelV2CallbackRequest;
import com.niiwoo.tripod.tiancheng.request.common.AgainstFakeBaseRequest;
import com.niiwoo.tripod.tiancheng.response.common.AgainstFakeV2Response;
import com.niiwoo.tripod.web.annotation.AuthIgnore;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by lujing on 2018/4/19.
 */
@Slf4j
@RestController
@RequestMapping("/tc")
@Api(tags = "5.1.5天秤借款反欺诈")
@AuthIgnore
public class LoanAntiFraudController {

    @Reference(version = "1.0.0")
    private LoanAntiFraudDubboService loanAntiFraudDubboService;


    /**
     * 卡贷天秤模型计算回调（RCE新模型）
     * @param againstFakeBaseRequest
     * @return
     */
    @ApiOperation("卡贷天秤模型计算回调（RCE新模型）")
    @RequestMapping(value = "/loanAntiFraud/callback", produces = "text/plain;charset=utf-8")
    public String kadaiModelCalculationCallback(HttpServletRequest servletRequest, @RequestBody AgainstFakeBaseRequest againstFakeBaseRequest) {
        String functionCode = servletRequest.getParameter("functionCode"); // URL中获取功能码
        log.info("卡贷天秤模型计算回调:functionCode={}, requestPrams={}", functionCode, JSON.toJSONString(againstFakeBaseRequest));
        if (StringUtils.isBlank(functionCode)) {
            throw new BizException("TC10001");
        }
        FunctionCodeEnum functionCodeEnum = FunctionCodeEnum.getByHeadFunctionCode(functionCode);
        if (functionCodeEnum == null) {
            throw new BizException("TC10002");
        }
        String msgBody = JSON.toJSONString(againstFakeBaseRequest.getMsg_body());
        String flowExecuteId = againstFakeBaseRequest.getReserve();
        loanAntiFraudBack(msgBody,flowExecuteId);
        AgainstFakeV2Response againstFakeV2Response = new AgainstFakeV2Response();
        againstFakeV2Response.setSession_id(againstFakeBaseRequest.getSession_id());
        againstFakeV2Response.setVersion(againstFakeBaseRequest.getVersion());
        againstFakeV2Response.setCode(AgainstFakeErrorCodeEnum.SUCCESS.getErrorCode());
        againstFakeV2Response.setCode_desc("success");
        return JSON.toJSONString(againstFakeV2Response);
    }

    private void loanAntiFraudBack(String msgBody,String flowExecuteId){
        AgainstFakeModelV2CallbackRequest againstFakeModelV2CallbackRequest = new AgainstFakeModelV2CallbackRequest();
        try{
            JSONObject msgBodyJSON = JSONObject.parseObject(msgBody);
            againstFakeModelV2CallbackRequest = msgBodyJSON.toJavaObject(AgainstFakeModelV2CallbackRequest.class);
        }catch (Exception ex){
            log.error("5.1.5天秤借款反欺诈回调对象装换异常{}",ex);
        }
        AgainstFakeModelV2CallbackRequestDTO againstFakeModelV2CallbackRequestDTO = new AgainstFakeModelV2CallbackRequestDTO();
        BeanUtils.copyProperties(againstFakeModelV2CallbackRequest, againstFakeModelV2CallbackRequestDTO);
        againstFakeModelV2CallbackRequestDTO.setFlowExecuteId(Long.valueOf(flowExecuteId));
        AgainstFakeModelV2CallbackRequest.AntiFraudResult antiFraudResult = againstFakeModelV2CallbackRequest.getResult();
        AgainstFakeModelV2CallbackRequestDTO.AntiFraudResult fraudResult = new AgainstFakeModelV2CallbackRequestDTO.AntiFraudResult();
        fraudResult.setDecision(againstFakeModelV2CallbackRequest.getResult().getDecision());
        AgainstFakeModelV2CallbackRequestDTO.Detail deta = new AgainstFakeModelV2CallbackRequestDTO.Detail();
        AgainstFakeModelV2CallbackRequest.Detail detail = antiFraudResult.getDetail();
        List<AgainstFakeModelV2CallbackRequest.BoolRule> boolRules = detail.getBool_rules();
        List<AgainstFakeModelV2CallbackRequestDTO.BoolRule> boolRuleList = new ArrayList<>();
        if (!boolRules.isEmpty()) {
            for (AgainstFakeModelV2CallbackRequest.BoolRule boolRule : boolRules) {
                AgainstFakeModelV2CallbackRequestDTO.BoolRule bool = new AgainstFakeModelV2CallbackRequestDTO.BoolRule();
                bool.setHit(boolRule.getHit());
                bool.setRule_name(boolRule.getRule_name());
                bool.setRule_id(boolRule.getRule_id());
                bool.setScore(boolRule.getScore());
                List<AgainstFakeModelV2CallbackRequest.BoolRuleData> boolRuleData = boolRule.getData();
                List<AgainstFakeModelV2CallbackRequestDTO.BoolRuleData> boolRuleDataList = new ArrayList<>();
                if (!boolRuleData.isEmpty()) {
                    for (AgainstFakeModelV2CallbackRequest.BoolRuleData boolData : boolRuleData) {
                        AgainstFakeModelV2CallbackRequestDTO.BoolRuleData ruleData = new AgainstFakeModelV2CallbackRequestDTO.BoolRuleData();
                        ruleData.setCellrule_id(boolData.getCellrule_id());
                        ruleData.setHit(boolData.getHit());
                        ruleData.setCellrule_name(boolData.getCellrule_name());
                        ruleData.setDecison_code(boolData.getDecison_code());
                        boolRuleDataList.add(ruleData);
                    }
                }
                bool.setData(boolRuleDataList);
                boolRuleList.add(bool);
            }
        }
        deta.setBool_rules(boolRuleList);
        List<AgainstFakeModelV2CallbackRequest.GroupRule> groupRules = detail.getGroup_rules();
        List<AgainstFakeModelV2CallbackRequestDTO.GroupRule> groupRuleList = new ArrayList<>();
        if (!groupRules.isEmpty()) {
            for (AgainstFakeModelV2CallbackRequest.GroupRule groupRule : groupRules) {
                AgainstFakeModelV2CallbackRequestDTO.GroupRule rule = new AgainstFakeModelV2CallbackRequestDTO.GroupRule();
                rule.setRule_id(groupRule.getRule_id());
                rule.setRule_name(groupRule.getRule_name());
                rule.setGroup_index(groupRule.getGroup_index());
                groupRuleList.add(rule);
            }
        }
        deta.setGroup_rules(groupRuleList);
        fraudResult.setDetail(deta);
        againstFakeModelV2CallbackRequestDTO.setResult(fraudResult);
        againstFakeModelV2CallbackRequestDTO.setDecision(againstFakeModelV2CallbackRequest.getResult().getDecision());
        log.info("反欺诈回调数据封装{}", JSONObject.toJSONString(againstFakeModelV2CallbackRequestDTO));
        RpcContext.getContext().asyncCall(() -> loanAntiFraudDubboService.loanAntiFraudBack(againstFakeModelV2CallbackRequestDTO));
    }


}
